//
//  AZLocationHandler.m
//  mobile
//
//  Created by abc on 2018/9/19.
//  Copyright © 2018年 azazie. All rights reserved.
//

#import <pthread/pthread.h>

#import "AZLocationHandler.h"
#import "WebsiteDataStore.h"

NSString *const APPLocationDidChangeNotification = @"APPLocationDidChangeNotification";

NSString *const LocationCookieName = @"sample_source";
NSString *const CurrencyCodeCookieName = @"currency-code";

static AZLocationHandler *defaultHandler = nil;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static NSString *const storeKey = @"com.azaize.location";
static NSString *const encodeKey = @"encode.location";

@interface AZLocationHandler ()

@property (nonatomic, strong) CLLocationManager *locator;

@end

@implementation AZLocationHandler

+ (AZLocationHandler *)defaultHaandler {
    
    pthread_mutex_lock(&mutex);
    {
        if (!defaultHandler)
        {
            NSData *encodedObject = [[NSUserDefaults standardUserDefaults] objectForKey:storeKey];
            if (encodedObject)
            {
                defaultHandler = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
            }
            else
            {
                defaultHandler = [[AZLocationHandler alloc] initWithLocation:AZLocationAddress_America];
                NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:defaultHandler];
                [[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:storeKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            [AZLocationHandler setHandelConfig:defaultHandler];
        }
    }
    pthread_mutex_unlock(&mutex);
    return defaultHandler;
}

+ (BOOL)isAmericaLocated {
    return [AZLocationHandler defaultHaandler].location == AZLocationAddress_America;
}

+ (BOOL)isCanadaLocated {
    return [AZLocationHandler defaultHaandler].location == AZLocationAddress_Canada;
}

+ (BOOL)supportsSecureCoding {
    return YES;
}

+ (void)setLocation:(NSString *)countryStr {
    AZLocationAddress location = [AZLocationHandler configLocation:countryStr];
    pthread_mutex_lock(&mutex);
    {
        if (location == AZLocationAddress_unKnow)
        {
            pthread_mutex_unlock(&mutex);
            [[NSNotificationCenter defaultCenter] postNotificationName:APPLocationDidChangeNotification object:nil userInfo:nil];
            return ;
        }
        if (defaultHandler && defaultHandler.location == location)
        {
            pthread_mutex_unlock(&mutex);
            [[NSNotificationCenter defaultCenter] postNotificationName:APPLocationDidChangeNotification object:nil userInfo:nil];
            return ;
        }
        
        AZLocationHandler *newLocation = [[AZLocationHandler alloc] initWithLocation:location];
        if (newLocation)
        {
            defaultHandler.location = newLocation.location;
            NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:newLocation];
            [[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:storeKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else
        {
            defaultHandler.location = AZLocationAddress_America;
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:storeKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        [AZLocationHandler setHandelConfig:defaultHandler];
    }
    pthread_mutex_unlock(&mutex);
    [[NSNotificationCenter defaultCenter] postNotificationName:APPLocationDidChangeNotification object:nil userInfo:nil];
}

+(void)setHandelConfig:(AZLocationHandler*)defaultHandler {
    NSString *domain = [AZLocationHandler currentDomainString:defaultHandler.location];
    NSString *countryCode = [AZLocationHandler getCountryCode:defaultHandler.location];
    [AZLocationHandler setCookie:defaultHandler.location countryCode:countryCode Domain:domain];
}

+ (void)setCookie:(AZLocationAddress)loc countryCode:(NSString *)countryStr Domain:(NSString *)domain {
    if (!domain) {
        domain = [AZLocationHandler currentDomainString:[AZLocationHandler defaultHaandler].location];
    }
    [WebsiteDataStore setCookieName:LocationCookieName
                              value:countryStr
                             domain:domain];
    [WebsiteDataStore setCookieName:CurrencyCodeCookieName
                              value:[AZLocationHandler getCurrencyCode:loc]
                             domain:domain];
}

// 定位相关逻辑开始
+ (void)startDefaultLocat {
    AZLocationHandler *handler = [AZLocationHandler defaultHaandler];
    handler.locator = [[CLLocationManager alloc] init];
    handler.locator.desiredAccuracy = kCLLocationAccuracyBest;
    handler.locator.delegate = handler;
    [handler.locator requestWhenInUseAuthorization];
    [handler.locator startUpdatingLocation];
}

-(void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager
{
    [self authorizationStatus:manager.authorizationStatus];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    [self authorizationStatus:status];
}

-(void)authorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
            case kCLAuthorizationStatusNotDetermined://---
        {
            /* 用户尚未决定是否启用定位服务 */
            break;
        }
            case kCLAuthorizationStatusRestricted:
        {
            /* 没有获得用户授权 */
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SelectCountryNotification" object:nil];
        }
            case kCLAuthorizationStatusDenied://---
        {
            /* 用户禁止使用定位或者定位服务处于关闭状态 */
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AutoShowSweepstakesNotificationName" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SelectCountryNotification" object:nil];
            break;
        }
            case kCLAuthorizationStatusAuthorizedAlways:
        {
            /* 前台、后台定位授权 */
            break;
        }
            case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            /* 前台定位授权 */
            break;
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [self.locator stopUpdatingLocation];
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    CLLocation *currentLocation = [locations lastObject];
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        NSLog(@"没有地址返回");
        if (placemarks.count >0)
        {
            CLPlacemark * placemark = placemarks.firstObject;
            NSString *ISOcountryCode = placemark.ISOcountryCode;
            [AZLocationHandler setLocation:ISOcountryCode];
        }
        else if (error == nil&&placemarks.count == 0)
        {
            NSLog(@"没有地址返回");
        }
        else if (error)
        {
            NSLog(@"location error:%@",error);
        }
        //抽奖活动
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AutoShowSweepstakesNotificationName" object:nil];
    }];
}
// 定位相关逻辑结束

#pragma mark - init & encode functions
- (instancetype)initWithLocation:(AZLocationAddress)location {
    if (self = [super init]) {
        _location = location;
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    AZLocationAddress location = [[aDecoder decodeObjectForKey:encodeKey] integerValue];
    return [self initWithLocation:location];
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:[NSNumber numberWithInteger:self.location] forKey:encodeKey];
}

- (instancetype)copyWithZone:(NSZone *)zone {
    return [[AZLocationHandler alloc] initWithLocation:self.location];
}
+ (NSString *)currentDomainString {
    return [AZLocationHandler currentDomainString:[AZLocationHandler defaultHaandler].location];
}
+ (NSString *)currentDomainString:(AZLocationAddress)loc {
    if (loc == AZLocationAddress_Canada) {
        return @".azazie.ca";
    } else {
        return @".azazie.com";
    }
}
+(AZLocationAddress)configLocation:(NSString *)countryStr {
    AZLocationAddress loc;
    if ([countryStr isEqualToString:@"US"]) {
        loc = AZLocationAddress_America;
    } else if ([countryStr isEqualToString:@"CA"]) {
        loc = AZLocationAddress_Canada;
    } else if ([countryStr isEqualToString:@"AU"]) {
        loc = AZLocationAddress_Au;
    } else if ([countryStr isEqualToString:@"GB"]) {
        loc = AZLocationAddress_Gb;
    } else {
        loc = AZLocationAddress_unKnow;
    }
    return loc;
}
+ (NSString *)getCurrencyCode {
    return [AZLocationHandler getCurrencyCode:[AZLocationHandler defaultHaandler].location];
}
+ (NSString *)getCurrencyCode:(AZLocationAddress)loc {
    if (loc == AZLocationAddress_America) {
        return @"USD";
    } else if(loc == AZLocationAddress_Canada) {
        return @"CAD";
    } else if(loc == AZLocationAddress_Au) {
        return @"AUD";
    } else if(loc == AZLocationAddress_Gb) {
        return @"GBP";
    } else {
        return @"";
    }
}

+ (NSString *)getCountryCode
{
    return [AZLocationHandler getCountryCode:[AZLocationHandler defaultHaandler].location];
}

+ (NSString *)getCountryCode:(AZLocationAddress)loc {
    if (loc == AZLocationAddress_America) {
        return @"US";
    } else if(loc == AZLocationAddress_Canada) {
        return @"CA";
    } else if(loc == AZLocationAddress_Au) {
        return @"AU";
    } else if(loc == AZLocationAddress_Gb) {
        return @"GB";
    } else {
        return @"";
    }
}
@end
